package com.jsy.mqhelper.charlotterpc.protocol;

import com.jsy.mqhelper.common.util.JsonUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;

/**
 * @author: SongyangJi
 * @description:
 * @since: 2021/10/8
 */

@Data
@NoArgsConstructor
public class ObjectWrapper {

    private String stringifyObject;

    private String className;

    public ObjectWrapper(Object object) {
        if (object != null) {
            this.stringifyObject = JsonUtil.stringify(object);
            this.className = object.getClass().getName();
        }
    }


    public Object unwrap() {
        if (!StringUtils.hasLength(stringifyObject) || !StringUtils.hasLength(className)) {
            return null;
        }

        Class<?> clazz;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e.getMessage());
        }
        return JsonUtil.parse(stringifyObject, clazz);
    }

    public <T> T parse(Class<T> valueType) {
        Class<?> clazz;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e.getMessage());
        }
        if (clazz != valueType) {
            throw new RuntimeException("class not matched");
        }
        return JsonUtil.parse(stringifyObject, valueType);
    }

    public static ObjectWrapper wrap(Object object) {
        return new ObjectWrapper(object);
    }

    public static ObjectWrapper[] wrap(Object[] objects) {
        if (objects == null) {
            return new ObjectWrapper[0];
        }
        int len = objects.length;
        ObjectWrapper[] objectWrappers = new ObjectWrapper[len];
        for (int i = 0; i < len; i++) {
            objectWrappers[i] = ObjectWrapper.wrap(objects[i]);
        }
        return objectWrappers;
    }

}
